/**
 * 自定义电子围栏
 */
class CustomFence extends BMap.Polygon {
  constructor({ points, users, marker, infoBox, fenceName, fenceID }) {
    super(points, {
      strokeColor: 'red',
      strokeWeight: 2,
      strokeOpacity: 0.5,
      strokeStyle: 'dashed',
      fillColor: 'transparent',
      fillOpacity: 1,
    });
    this.points = points; // 点位
    this.users = users || null;
    this.fenceID = fenceID || null;
    this.fenceName = fenceName || '';
    this.title = '';
    this.marker = marker || null;
    this.infoBox = infoBox || null; // 信息窗口
  }

  addFence(map, { size }, callback) {
    if (!map) {
      console.error('map对象不能为空');
      return;
    }
    map.addOverlay(this);

    size = size || 40;
    let icon = new BMap.Icon(
      'static/bmap/images/flag.png',
      new BMap.Size(size, size),
      {
        anchor: new BMap.Size(size / 3, size),
        imageSize: new BMap.Size(size, size),
        infoWindowAnchor: new BMap.Size(size / 2, 0),
      }
    );

    let marker = (this.marker = new BMap.Marker(this.points[0], { icon })); // 创建标注
    marker.addEventListener('click', e => {
      e.domEvent.stopPropagation();
      map.panTo(e.point);
      // if (this.infoBox) {
      //   this.closeInfoBox();
      //   return;
      // }
      callback(this);
    });
    marker.addEventListener('mouseover', e => {
      e.domEvent.stopPropagation();
      callback(this);
    });
    marker.addEventListener('mouseout', e => {
      e.domEvent.stopPropagation();
      callback(this);
    });
    map.addOverlay(marker);
  }

  removeFence() {
    try {
      if (this.infoBox) this.map.removeOverlay(this.infoBox);
      if (this.marker) this.map.removeOverlay(this.marker);
      this.map.removeOverlay(this);
    } catch (error) {}

    this.infoBox = null;
    this.marker = null;
  }

  closeInfoBox() {
    if (this.infoBox) this.infoBox.close();
    this.infoBox = null;
  }

  setInfoBox(infoBox) {
    this.infoBox = infoBox;
  }
}

export default CustomFence;
